#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os

from django.db import IntegrityError
from django.utils.translation.trans_null import gettext
from rest_framework import status, viewsets, serializers
from rest_framework.decorators import action, permission_classes
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema, extend_schema_view

from tools.permissions import IsTokenValid
from tools.token_tools import CustomTokenTool, generate_is_user_token
from models.models import User
from tools.password_hasher import hash_password, verify_password
from django.utils.translation import gettext as _
from django.utils.translation import get_language



class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    confirm_password = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'confirm_password')  # 新增 id（生成 Token 需用）

    def validate(self, data):
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError(_("两次输入的密码不一致"))
        return data

    def create(self, validated_data):
        validated_data.pop('confirm_password')
        # 使用自定义加密替代 Django 的 make_password
        return User.objects.create(** validated_data)

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)
from rest_framework.request import Request
@extend_schema(tags=[_("用户管理")])
@extend_schema_view(
    list=extend_schema(summary=_('获取用户列表（需有效 Token）')),
    retrieve=extend_schema(summary=_('获取用户详情（需有效 Token）')),
)
class UserViewSet(viewsets.ViewSet):
    # 权限分配：登录/注册允许匿名访问，其他接口需有效 Token
    permission_classes_by_action = {
        'register': [],  # 匿名可访问
        'login': [],  # 匿名可访问
        'list': [IsTokenValid],  # 需有效 Token
        'retrieve': [IsTokenValid],  # 需有效 Token
    }
    queryset = User.objects.all()

    def get_permissions(self):
        """动态获取当前接口的权限类"""
        return [perm() for perm in self.permission_classes_by_action.get(self.action, [])]

    # -------------------------- 注册接口：生成 Token 返回 --------------------------
    @extend_schema(
        request=RegisterSerializer,
        responses={
            201: {"type": "object", "properties": {"token": {"type": "string"}, "user_id": {"type": "integer"}}}},
        summary=_("用户注册（匿名可访问）"),
    )
    @action(detail=False, methods=['post'], url_path='register')
    def register(self, request):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            # 生成自定义 Token（用用户 ID 关联）
            token = CustomTokenTool.generate_token(user_id=user.id)
            return Response(
                {"token": token, "user_id": user.id, "username": user.username},
                status=status.HTTP_201_CREATED
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    @extend_schema(
        request=LoginSerializer,
        responses={
            200: {"type": "object", "properties": {"token": {"type": "string"}, "user_id": {"type": "integer"}}}},
        summary=_("用户登录（匿名可访问）")
    )
    @action(detail=False, methods=['post'], url_path='login')
    def login(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        # 1. 校验输入
        if not username or not password:
            return Response({'error': _('用户名和密码不能为空')}, status=status.HTTP_400_BAD_REQUEST)
        # 2. 查询用户并校验密码
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return Response({'error': _('用户名不存在')}, status=status.HTTP_400_BAD_REQUEST)
        except IntegrityError:  # 避免用户名重复（理论上 username 已设 unique，此处兜底）
            return Response({'error': _('用户名重复')}, status=status.HTTP_400_BAD_REQUEST)

        if verify_password(password, user.password):  # 注意参数顺序：原始密码在前，哈希密码在后
            token = generate_is_user_token(request,user)
            return Response(
                {"token": token, "user_id": user.id, "username": user.username},
                status=status.HTTP_200_OK
            )
        return Response({'error': _('用户名或密码错误')}, status=status.HTTP_400_BAD_REQUEST)

    def list(self, request):
        print(f"当前登录用户：{request.user.username}")
        users = self.queryset.all()
        serializer = RegisterSerializer(users, many=True)
        return Response(serializer.data)

    @extend_schema(
        responses={200: {"type": "object", "properties": {"message": {"type": "string"}}}},
        summary="用户登出（需有效 Token）"
    )
    @action(detail=False, methods=['post'], url_path='logout')
    def logout(self, request):
        print("!")
        # print(f"当前登录用户：{request.username}")
        print("翻译路径：", os.environ.get('DJANGO_LOCALE_PATHS'))  # 查看 Django 读取的路径
        print("译文：", gettext("未提供有效 Token"))  # 若输出日语则成功
        # 从请求头获取自定义 Token
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        if not auth_header:
            return Response({"error":  _("未提供有效 Token")}, status=status.HTTP_400_BAD_REQUEST)

        # 假设 Token 格式为 "Bearer <token>"
        try:
            token = auth_header.split(' ')[1]
        except IndexError:
            return Response({"error":  _("Token 格式错误")}, status=status.HTTP_400_BAD_REQUEST)

        if token:
            CustomTokenTool.delete_token(token)
            return Response({"message":  _("登出成功，Token 已失效")}, status=status.HTTP_200_OK)

        return Response({"error":  _("未提供有效 Token")}, status=status.HTTP_400_BAD_REQUEST)